package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.text.html.HTMLDocument;
import java.io.IOException;
import java.util.Iterator;

public class UpdateCartQuantitiesServlet extends HttpServlet {
    public static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private Cart cart;
    private Iterator<CartItem> cartItems;
    private LogService logService;
    private Account account;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        cart = (Cart) session.getAttribute("cart");
        account = (Account)session.getAttribute("account");

        cartItems = cart.getCartItems();
        while (cartItems.hasNext()){
            CartItem cartItem = (CartItem) cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            try {
                int quantity = Integer.parseInt((String) request.getParameter(itemId));
                cart.setQuantityByItemId(itemId, quantity);
                if (quantity < 1) {
                    cartItems.remove();
                }
                if (account != null){
                    logService = new LogService();
                    logService.insertLog("Update Item in Cart","Item:"+itemId, account.getUsername());
                } else {
                    logService = new LogService();
                    logService.insertLog("Update Item in Cart","Item:"+itemId, "null");
                }
            } catch (Exception e) {
                //ignore parse exceptions on purpose
            }        }

        session.setAttribute("cart",cart);
        request.getRequestDispatcher(VIEW_CART).forward(request,response);
    }
}
